var $tbody = $("#sample-table-1 tbody");
var allStation = [];
var allAdminRoles = [];


jQuery(function ($) {
    $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
});
var allStation = [];
var nowdate = new Date();
var oneweekdate = new Date(nowdate-7*24*3600*1000);
$("#startdate").val(beginDate(oneweekdate));
$("#enddate").val(endDate(nowdate));

function beginDate(date) {
    return endDate(date);
};

function endDate(date) {
    return date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2);
};

console.log('report');
// 初始化table
$("#report_table").bootstrapTable({
    // 'url': '../serviceType/findAll',
    'url': '/community/forummessage/queryAllReportForumMsg',
    'toolbar': $('div[data-name="btnCtl"]'),
    'queryParams': queryParams,
    'cache':false,
    'sidePagination': 'server',
    'toolbarAlign': 'right',
    'undefinedText': '-',
    'striped': true,
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        return {
            'total': resb.data.total,
            'rows': resb.data.rows
        }
    },
    'onCheck': function() {
        $("#dataInfo").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("#dataInfo").attr("disabled", 'true');
    },
    'onPageChange': function() {
        if($("#report_table").bootstrapTable('getSelections')[0]){
            $("#report_table").bootstrapTable('uncheckBy', {
                field: 'typeId',
                values: [$("#report_table").bootstrapTable('getSelections')[0].typeId]
            });
        }

    },
    'columns': [{
        'checkbox': true,
        // 'class': 'hide'
    },
        {
            'field': 'forumMsgId',
            'title': '用户ID',
            'align': 'center',
            'class': 'hide forumMsgId'
        },{
            'field': 'nickName',
            'title': '昵称',
            'align': 'center'
        },{
            'field': 'msgType',
            'title': '帖子类型',
            'align': 'center',
            'formatter': function (msgType) {
                var obj = {'msg':'帖子','shareMsg':'分享的帖子','shareNews':'分享的新闻','shareGroup':'分享的小组','shareVideo':'分享的视频','groupMsg':'小组的帖子','shortVideo':'短视频','threeDimensionalVideo': '3D视频'};
                return obj[msgType];
            }
        },{
            'field': 'msgContent',
            'title': '帖子内容',
            'width':300,
            'align': 'center'

        },{
            'field': 'reportCount',
            'title': '举报次数',
            'align': 'center'

        },{
            'field': 'msgDelete',
            'title': '是否删除',
            'align': 'center',
            'formatter': function (msgDelete) {
                var obj = {'0': '未删除', '1': '已删除'};
                var html = "<span>"+obj[msgDelete]+"</span>";
                if(msgDelete === 1) {
                    html = "<span style='color:red'>"+obj[msgDelete]+"</span>";
                }
                return html;
            }
        },{
            'field': 'forumHandle',
            'title': '举报状态',
            'align': 'center',
            'formatter': function (forumHandle) {
                var obj = {'forumHandleNo':'未处理','forumHandleYesNotDelete':'已处理不删除','forumHandleYesAndDelete':'已处理删除'};
                return obj[forumHandle];
            }
        },{
            'field': 'handlePerson',
            'title': '操作人',
            'align': 'center'
        },{
            'field': 'createDate',
            'title': '创建日期',
            'align': 'center'
        },{
            'title': '操作',
            'align': 'center',
            'formatter': function () {
                return "<button type='button' class='hand btn btn-sm btn-success' >查看详情</button>";
            }
        }

    ]
});
// });

//请求服务数据时所传参数
function queryParams(params){
    return {
        'forumHandle' : $("#handle-status").val(),
        limit : params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        offset : params.offset/params.limit+1 //当前页面,默认是上面设置的1(pageNumber)
    }
}


//根据操作结果查询帖子
$("#handle-status").change(function () {
    reportQuery($("#handle-status").val());
});

// 查询举报信息
var _forumMsgId = "";
// var flag = false;
$(document).on('click', '.hand', function () {
   $("#reportModal").modal('show');
    _forumMsgId = $(this).parent().siblings(".forumMsgId").html();
    getReason($(this).parent().siblings(".forumMsgId").html());
    // getReason("0e56e22d47ba42c59741ea89b2e5f963");
});

// 处理并删除
$(".delete").click(function () {
    $("#deleteModal").modal('show');
    $("#deleteModal .modal-body").html("<p>确认是否删除,误删后,请联系管理员恢复</p>");
});

$(".deleteConfirm").click(function () {
    handle(_forumMsgId, "forumHandleYesAndDelete", sessionStorage.getItem('handlePerson'));
});

// 处理不删除
$(".noDelete").click(function () {
    handle(_forumMsgId, "forumHandleYesNotDelete", sessionStorage.getItem('handlePerson'));
});


//处理举报的帖子
function handle(forumMsgId, forumHandle, handlePerson) {
    $.ajax({
        type: "GET",
        url: "/community/forumreport/dealReportForumMessage?forumMsgId=" + forumMsgId + "&forumHandle=" + forumHandle+"&handlePerson="+handlePerson,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            alert("处理成功！！");
            $("#report_table").bootstrapTable("refresh");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

/**
 * 举报的帖子查询ajax
 * @param name 请求查询的服务人员
 */
function reportQuery(forumHandle) {
    if (($("#inputStation").val() == '')) {
        $('#report_table').bootstrapTable('refreshOptions', {pageNumber: 1, pageSize: globalPageSize});
    } else {
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "GET",
            url: "/community/forummessage/queryAllReportForumMsg?forumHandle="+forumHandle+"&offset=1&limit="+globalPageSize,
            // dataType: 'json',
            'sidePagination': 'server',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", localStorage.token);
            },
            success: function (resb) {
                if (resb.data && resb.data.length != 0) {
                    $("#report_table").bootstrapTable('load', {'total': resb.data.total, 'rows': resb.data.rows});
                } else {
                    $("#report_table").bootstrapTable('removeAll');
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}

/**
 * 举报详情查询ajax
 * @param forumMsgId 请求查询的t帖子ID
 */
function getReason(forumMsgId) {
    $("#reportReason_table").bootstrapTable('destroy');
    $("#reportReason_table").bootstrapTable({
        // 'url': '../serviceType/findAll',
        'url': '/community/forumreport/findForumreportByMsgId?forumMsgId='+forumMsgId,
        'toolbar': $('div[data-name="btnCtl"]'),
        // 'queryParams': queryParams,
        'cache':false,
        'sidePagination': 'server',
        'toolbarAlign': 'right',
        'undefinedText': '-',
        'striped': true,
        'pagination': true,
        'sortable': true, //是否启用排序
        'sortOrder': "asc", //排序方式
        // 'pageSize': globalPageSize,
        'pageList': [],
        'clickToSelect': true,
        'singleSelect': true,
        'smartDisplay': true,
        'ajaxOptions':{
            headers: {"Authorization": localStorage.token}
        },
        'responseHandler': function (resb) {
            console.log(resb);
            if(resb.data && resb.data.length > 0) {
                if(resb.data[0].forumHandle === "forumHandleYesAndDelete" || resb.data[0].forumHandle === "forumHandleYesNotDelete") {
                    $(".delete").attr('disabled', true);
                    $(".noDelete").attr('disabled', true);
                }else {
                    $(".delete").attr('disabled', false);
                    $('.noDelete').attr("disabled",false);
                };
            };
            return {
                'total': resb.data.length,
                'rows': resb.data
            }
        },
        'columns': [{
            'checkbox': true,
            'class': 'hide'
        },
            {
                'field': 'reportedUserId',
                'title': '被举报用户ID',
                'width':200,
                'align': 'center',
                'class': 'hide'
            },{
                'field': 'forumReportReason',
                'title': '举报原因',
                'width': 300,
                'align': 'center'

            },{
                'field': 'createDate',
                'title': '创建日期',
                'width' : 325,
                'align': 'center'
            }
        ]
    });
};

// 查看帖子详情
$("#dataInfo").click(function () {
   var tableData = $("#report_table").bootstrapTable("getSelections")[0];
   console.log(tableData)
    window.open('fatie/detail.html?id='+tableData.forumMsgId);
});

/**
 * 角色操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {adminId: int}]
 * @param async/scync [default async]
 */
function adminManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false : async = true;
    if (action === 'add') {
        url = '../admin/addAdmin';
    } else if (action === 'update') {
        url = '../admin/updateAdmin';
    } else {
        url = '../admin/deleteAdmin';
    }

    $.ajaxSetup({cache:false});
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        async: async,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function (resb) {
            alert(resb.message);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}